//
//  HomeController.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/5/23.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import SwiftyJSON
import FSPagerView
import MJRefresh

class HomeController: CBBaseViewController {
    ///公司名称
    @IBOutlet weak var lblCompanyName: UILabel!
    ///公司描述
    @IBOutlet weak var lblCompanyDesc: UILabel!
    
    @IBOutlet weak var vwScroll: UIScrollView!
    
    @IBOutlet weak var cltProduct: UICollectionView!
    let CELL_ID:String = "PRODUCT_CELL_ID"
    let BANNER_CELL_ID = "home_banner_cell"
    
    @IBOutlet weak var vwBannerContentView: UIView!
    
    var pageView:FSPagerView!
    var arrProduct:[HomeProductModel] = [HomeProductModel]()
    var arrBannerModel:[HomeBannerModel] = [HomeBannerModel]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "百汇聚"
        self.cltProduct.register(UINib(nibName: "HomeProductCell", bundle: nil), forCellWithReuseIdentifier: CELL_ID)
        
        pageView = FSPagerView(frame: .zero)
        pageView.dataSource = self
        pageView.delegate = self
        pageView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: BANNER_CELL_ID)
        pageView.automaticSlidingInterval = 3.0
        vwBannerContentView.addSubview(pageView)
        pageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        vwScroll.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(initData))
        initData()
    }
    
    @objc func initData() {
        var initCount = 3
        let blkInit = { [unowned self] in
            initCount -= 1
            if initCount <= 0 {
                self.vwScroll.mj_header.endRefreshing()
            }
        }
        NetworkTool.requestData(url: ActionURL.GET_HOME_BANNER, param: nil)
            .map { (json) -> [HomeBannerModel]? in
                return HomeBannerModel.mj_objectArray(withKeyValuesArray: json["rows"].arrayObject) as? [HomeBannerModel]
            }.catchErrorJustReturn(nil)
            .subscribe(onNext:{ [unowned self] opArr in
                if let dataArr = opArr {
                    self.arrBannerModel = dataArr
                    self.pageView.reloadData()
                }
                blkInit()
            }).disposed(by: disposeBag)
        
        NetworkTool.requestData(url: ActionURL.GET_HOME_PRODUCT_DESC, param: nil)
            .map { (json) -> [HomeProductModel]? in
                return HomeProductModel.mj_objectArray(withKeyValuesArray: json["rows"].arrayObject) as? [HomeProductModel]
            }.catchErrorJustReturn(nil)
            .subscribe(onNext:{ [unowned self] opArr in
                if let dataArr = opArr {
                    self.arrProduct = dataArr
                    self.cltProduct.reloadData()
                }
                blkInit()
            }).disposed(by: disposeBag)
        
        NetworkTool.requestData(url: ActionURL.HOME_GET_INFO, param: nil)
            .map { (json) -> JSON? in
                return json
            }.catchErrorJustReturn(nil)
            .subscribe(onNext: { opJson in
                if let json = opJson {
                    let data = json["rows"].dictionaryValue
                    self.lblCompanyName.text = data["companyName"]?.stringValue
                    self.lblCompanyDesc.text = data["companyDesc"]?.stringValue
                }
                blkInit()
            }).disposed(by: disposeBag)
    }
    
}

extension HomeController: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrProduct.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:HomeProductCell = (collectionView.dequeueReusableCell(withReuseIdentifier: CELL_ID, for: indexPath) as? HomeProductCell) ?? HomeProductCell()
        cell.model = arrProduct[indexPath.row]
        return cell
    }
    
}

extension HomeController: FSPagerViewDataSource, FSPagerViewDelegate {
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return arrBannerModel.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: BANNER_CELL_ID, at: index)
        cell.imageView?.kf.setImage(with: URL(string: ActionURL.HOST + arrBannerModel[index].img), placeholder: UIImage(named: "bg_place_holder"), completionHandler: nil)
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        if arrBannerModel[index].url.isEmpty {
            return
        }
        
        let webVc = CBWebViewController()
        webVc.title = "百汇聚"
        webVc.urlAddress = arrBannerModel[index].url
        webVc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(webVc, animated: true)
    }
    
}
